package com.phenix.network.response

import com.phenix.network.base.Envelope
import com.phenix.network.error.BusinessException
import retrofit2.Call
import retrofit2.CallAdapter
import retrofit2.Retrofit
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

class NetworkResponseAdapterFactory(
    private val failureHandler: FailureHandler?,
    private val envelope: Envelope
) : CallAdapter.Factory() {

    interface FailureHandler {
        fun onFailure(throwable: BusinessException): Boolean
    }

    override fun get(
        returnType: Type,
        annotations: Array<out Annotation>,
        retrofit: Retrofit
    ): CallAdapter<*, *>? {
        if (Call::class.java != getRawType(returnType)) {
            return null
        }
        check(returnType is ParameterizedType) {
            "return type must be Parameterized as Call<NetworkResponse<<Foo>> or Call<NetworkResponse<out Foo>"
        }
        val responseType = getParameterUpperBound(0, returnType)
        if (getRawType(responseType) != NetworkResponse::class.java) {
            return null
        }

        check(responseType is ParameterizedType) {
            "response must be Parameterized as NetworkResponse<<Foo>> or NetworkResponse<out Foo>"
        }

        return NetworkResponseAdapter<Any>(responseType, failureHandler, envelope)
    }


}
